package com.kehutong.message.service;

import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.orm.jdbc.connection.ThreadLocalCache;
import org.coraframework.orm.util.Enums;
import org.coraframework.util.Objects;
import com.kehutong.common.DoveClient;
import com.kehutong.common.errcode.Result;
import com.kehutong.common.urlconfig.FileUrlConfig;
import com.kehutong.message.enums.WebWorkApiSuffix;
import com.kehutong.message.enums.WelComeType;
import com.kehutong.message.urlConfig.WorkerUrlConfig;

/**
 * 发送消息
 * 
 * @author liuzhen (liuxing521a@163.com)
 * @createTime 2020年5月20日 上午10:52:03
 */
@WebService("/message/webwork")
public class WebWorkMessageService {

	protected static final Logger logger = LoggerFactory.getLogger(WebWorkMessageService.class);
	
	@Inject
	private WorkerUrlConfig workerConfig;
	@Inject
	private FileUrlConfig fileConfig;
	@Inject
	private DoveClient doveClient;

	private String getToken(){
		return null;
	}

	/**
	 * <p>微信消息-发欢迎消息</p>
	 * @param json
	 * @throws Exception
	 */
	@ReqMapping("/sendWelCome")
	public void sendWelCome(JSONObject json) throws Exception {
		String access_token = json.getString("access_token");
		String welcomeCode = json.getString("welcomeCode");
		String companyNo = json.getString("companyNo");

		ThreadLocalCache.current().setCorpId(companyNo);
		JSONObject welcomeJson = doveClient.post("/crm/material/welcome/getDefault", http -> {});
		logger.info("{}默认欢迎语：{}", companyNo, welcomeJson);
		JSONObject dataJson = welcomeJson.getJSONObject("data");
		if (Objects.isNull(dataJson)){
			return;
		}

		JSONObject requestJson = getWelcomeBody(welcomeCode, dataJson);
		logger.info("欢迎语请求企微参数：{}", requestJson.toJSONString());

		send(access_token, requestJson, WebWorkApiSuffix.SEND_WELCOME_MSG);

	}

	/**
	 * <p>微信消息-分享消息</p>
	 * @param json
	 * @throws Exception
	 */
	// @ReqMapping("/sendShare")
	public void sendShare(JSONObject json) throws Exception {
		String access_token = json.getString("access_token");

		send(access_token, getSendShare(json), WebWorkApiSuffix.ADD_MSG_TEMPLATE);
	}


	/**
	 * 应用消息-文本
	 * @param json
	 * companyNo：公司编号
	 * userId：指定接收消息的成员，成员ID列表（多个接收者用‘|’分隔，最多支持1000个）。 特殊情况：指定为”@all”，则向该企业应用的全部成员发送
	 * content：消息内容，最长不超过2048个字节，超过将截断（支持id转译）
	 * @return
	 */
	@ReqMapping("/sendAppText")
	public Object sendAppText(JSONObject json) {
		final String companyNo = json.getString("companyNo");
		try {
			if (Objects.isEmpty(json.getString("userId"))){
				String userId = getUserId(json.getString("uuid"), companyNo);
				if (Objects.isEmpty(userId))
					return Result.error(0, "找不到userId");

				json.put("userId", userId);
			}

			JSONObject agentJson = doveClient.post("/kht-bin/wwout/agent/get", http -> {
				http.addParam("companyNo", companyNo);
			});
			if (agentJson.getIntValue("code") != 200) {
				return Result.error(0, agentJson.getString("message"));
			}
			JSONObject data = agentJson.getJSONObject("data");
			String access_token = data.getString("access_token");
			String agentid = data.getString("agentid");

			return send(access_token, getSendAppText(json, agentid), WebWorkApiSuffix.MSG_SEND);
		} catch (Exception e){
			logger.error(e.getMessage(), e);
			return Result.error(0, e.getMessage());
		}
	}

	private String getUserId(String uuid, String companyNo){
		try {
			JSONObject result = doveClient.post("/kht-bin/wwout/getEmployeeByKhtId",(http)->{
				http.addParam("companyNo", companyNo);
				JSONObject body = new JSONObject();
				body.put("khtId", uuid);
				http.setBody(body.toJSONString());
			});

			if (result.getIntValue("code") == 200) {
				JSONObject jsonObject = result.getJSONObject("data");
				return jsonObject.getString("userId");
			} else {
				return null;
			}
		} catch (Exception e){
			logger.error(e.getMessage(), e);
			return null;
		}

	}

	//应用消息-分享
	@ReqMapping("/sendAppCard")
	public Object sendAppCard(JSONObject json) throws Exception {
		try {
			logger.info("sendAppCard开始请求企微：{}", json);
			final String companyNo = json.getString("companyNo");
			if (Objects.isEmpty(json.getString("userId"))){
				String userId = getUserId(json.getString("uuid"), companyNo);
				if (Objects.isEmpty(userId))
					return Result.error(0, "找不到userId");

				json.put("userId", userId);
			}

			JSONObject agentJson = doveClient.post("/kht-bin/wwout/agent/get", http -> {
				http.addParam("companyNo", companyNo);
			});
			if (agentJson.getIntValue("code") != 200) {
				return Result.error(0, agentJson.getString("message"));
			}
			JSONObject data = agentJson.getJSONObject("data");
			String access_token = data.getString("access_token");
			String agentid = data.getString("agentid");

			JSONObject tempJson = getSendAppCard(json, agentid);
			logger.info("sendAppCard开始请求企微：{}", tempJson.toJSONString());
			return send(access_token, tempJson, WebWorkApiSuffix.MSG_SEND);
		} catch (Exception e){
			logger.error(e.getMessage(), e);
			return Result.error(0, e.getMessage());
		}
	}

	private JSONObject getSendAppCard(JSONObject json, String agentid){
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("touser", json.getString("userId"));
		jsonObject.put("msgtype", "textcard");
		jsonObject.put("agentid", agentid);

		JSONObject cardText = new JSONObject();
		cardText.put("title", json.getString("title"));
		cardText.put("description", json.getString("content"));
		cardText.put("url", json.getString("appToUrl"));
		cardText.put("btntxt", "详情");

		jsonObject.put("textcard", cardText);

		return jsonObject;
	}

	private JSONObject getSendAppText(JSONObject json, String agentid){
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("touser", json.getString("userId"));
		jsonObject.put("msgtype", "text");

		jsonObject.put("agentid", agentid);

		JSONObject cont = new JSONObject();
		cont.put("content", json.getString("content"));
		jsonObject.put("text", cont);

		return jsonObject;
	}

	private JSONObject getSendShare(JSONObject json){
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("chat_type", "single");
		jsonObject.put("external_userid", json.getJSONArray("userIds"));

		JSONObject link = new JSONObject();
		link.put("title", json.getString("title"));
		link.put("desc", json.getString("desc"));
		link.put("picurl", fileConfig.getFile(json.getString("fileId")));
		link.put("url", json.getString("url"));
		jsonObject.put("link", link);

		return jsonObject;
	}

	private JSONObject getWelcomeBody(String welcome_code, JSONObject json) {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("welcome_code", welcome_code);

		switch (Enums.getEnum(WelComeType.class, json.getJSONObject("type").getString("id"))) {
		case TEXT:
			JSONObject text = new JSONObject();
			text.put("content", json.getString("content"));
			jsonObject.put("text", text);
			break;
		case SHARE:
			JSONObject link = new JSONObject();
			link.put("title", json.getString("title"));
			link.put("picurl", fileConfig.getFile(json.getString("picurl")));
			link.put("desc", json.getString("desc"));
			link.put("url", json.getString("url"));
			jsonObject.put("link", link);
			break;
		case ALL:
			JSONObject links = new JSONObject();
			links.put("title", json.getString("title"));
			links.put("picurl", fileConfig.getFile(json.getString("picurl")));
			links.put("desc", json.getString("desc"));
			links.put("url", json.getString("url"));
			jsonObject.put("link", links);

			JSONObject texts = new JSONObject();
			texts.put("content", json.getString("title"));
			jsonObject.put("text", texts);
			break;
		default:
			// donothing
			break;
		}
		return jsonObject;
	}

	/**
	 * 发送http请求
	 * @param access_token 对应企业微信的token
	 * @param json body
	 * @param pageSuffix 接口地址后缀
	 * @throws Exception
	 */
	private Object send(String access_token, JSONObject json, WebWorkApiSuffix pageSuffix) throws Exception {
		if (Objects.isEmpty(access_token)) {
			throw new Exception("不存在access_token");
		}

		JSONObject result = workerConfig.postFixed(pageSuffix.getSuffix(), http -> {
			http.addParam("access_token", access_token);
			http.setBody(json.toJSONString());
		});

		logger.info("发送欢迎语返回：{}", result);

		return result;
	}
}
